package com.yijdn.common.aspect;

import com.sun.org.apache.bcel.internal.generic.RETURN;
import com.yijdn.common.utils.ReturnModel;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.PrimitiveIterator;

/**
 * @author zww
 * @date 2018-03-25 11:47
 * <p>
 * Email 971762302@qq.com
 * <p>
 * Describe:
 */
@Component
@Aspect
public class MvcAspect {

    @Autowired
    private HttpServletRequest request;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        Object proceed = point.proceed();


        if (proceed instanceof Void) {
            return proceed;
        }

        if(proceed instanceof ModelAndView){
            return (ModelAndView)proceed;
        }

        ReturnModel returnModel = null;

        Enumeration<String> parameterNames = request.getParameterNames();
        Map<String,String> map = new HashMap<>(5);
        while (parameterNames.hasMoreElements()){
            String key = parameterNames.nextElement();
            map.put(key,request.getParameter(key));
        }


        if (proceed instanceof ReturnModel) {

            returnModel = (ReturnModel) proceed;

            if(!map.isEmpty()){
                returnModel.setParams(map);
            }

            return returnModel;
        }

        returnModel = ReturnModel.ok();
        returnModel.setData(proceed);
        returnModel.setParams(map);
        return returnModel;
    }
}
